home *** CD-ROM | disk | FTP | other *** search
/ Atari Mega Archive 2 / Atari Mega Archive CD - Volume 2.iso / minix / up1510b.tgz / up1510b / src / commands / head.c < prev    next >
C/C++ Source or Header  |  1990-07-15  |  1KB  |  71 lines

  1. /* head - print the first few lines of a file    Author: Andy Tanenbaum */
  2.  
  3. #include <stdio.h>
  4.  
  5. #define DEFAULT 10
  6.  
  7. main(argc, argv)
  8. int argc;
  9. char *argv[];
  10. {
  11.   FILE *f;
  12.   int n, k, nfiles;
  13.   char *ptr;
  14.  
  15.   /* Check for flag.  Only flag is -n, to say how many lines to print. */
  16.   k = 1;
  17.   ptr = argv[1];
  18.   n = DEFAULT;
  19.   if (argc > 1 && *ptr++ == '-') {
  20.     k++;
  21.     n = atoi(ptr);
  22.     if (n <= 0) usage();
  23.   }
  24.   nfiles = argc - k;
  25.  
  26.   if (nfiles == 0) {
  27.     /* Print standard input only. */
  28.     do_file(n, stdin);
  29.     exit(0);
  30.   }
  31.  
  32.   /* One or more files have been listed explicitly. */
  33.   while (k < argc) {
  34.     if (nfiles > 1) printf("==> %s <==\n", argv[k]);
  35.     if ((f = fopen(argv[k], "r")) == NULL)
  36.         printf("head: cannot open %s\n", argv[k]);
  37.     else {
  38.         do_file(n, f);
  39.         fclose(f);
  40.     }
  41.     k++;
  42.     if (k < argc) printf("\n");
  43.   }
  44.   exit(0);
  45. }
  46.  
  47.  
  48.  
  49. do_file(n, f)
  50. int n;
  51. FILE *f;
  52. {
  53.   int c;
  54.  
  55.   /* Print the first 'n' lines of a file. */
  56.   while (n) switch (c = getc(f)) {
  57.         case EOF:
  58.         return;
  59.         case '\n':
  60.         --n;
  61.         default:    putc((char) c, stdout);
  62.     }
  63. }
  64.  
  65.  
  66. usage()
  67. {
  68.   fprintf(stderr, "Usage: head [-n] [file ...]\n");
  69.   exit(1);
  70. }
  71.